package com.cz.second.kill.service.impl;

import com.cz.second.kill.persistence.dao.CommodityMapper;
import com.cz.second.kill.service.ISecondKill;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>利用mysql乐观锁进行模拟秒杀</p>
 * <pre>
 * @author gitamacai
 * @date 2019/12/5 15:14
 * </pre>
 */
@Service("mysqlSecondKillImpl")
@Slf4j
public class MysqlSecondKillImpl implements ISecondKill {

    @Autowired
    private CommodityMapper commodityMapper;

    @Override
    public Integer kill(String uid) {
        Integer commodityId = commodityMapper.selectIdToKill();
        if (commodityId == null) {
            // 没有符合条件的商品进行秒杀
            return 0;
        }
        try {
            Integer row = commodityMapper.updateWinUid(commodityId, uid);
            if (row > 0) {
                // 如果更新成功则认为是秒杀成功
                return commodityId;
            }
        } catch (Exception e) {
            log.error("秒杀失败");
        }
        // 进行秒杀失败
        return 0;
    }
}
